package com.cherry.ssm.controller;

import com.cherry.ssm.bean.Employee;
import com.cherry.ssm.bean.Msg;
import com.cherry.ssm.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 单个删除和批量删除合并
     * 批量删除:1-2-3
     * 单个删除:1
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmpById(@PathVariable("ids") String ids) {
        //批量删除
        if (ids.contains("-")) {
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            for (String s : str_ids) {
                del_ids.add(Integer.parseInt(s));
            }
            employeeService.deleteBatch(del_ids);
        } else { //单个删除
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmpById(id);
        }
        return Msg.success();
    }

    /**
     * 根据员工ID修改数据
     * 注意value="/emp/{empId}"这里要和Employee中的empId属性同名
     *
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateEmpById(Employee employee) {
        System.out.println("最新的员工数据:" + employee);
        employeeService.updateEmpById(employee);
        return Msg.success();
    }

    /**
     * 按照员工ID查询数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmpById(@PathVariable("id") Integer id) {
        Employee employee = employeeService.getEmpById(id);
        return Msg.success().add("emp", employee);
    }

    /**
     * 检验用户名是否可用
     * 返回状态码
     *
     * @param empName
     * @return
     */
    @RequestMapping("/checkUser")
    @ResponseBody
    public Msg checkUser(@RequestParam("empName") String empName) {
        //先判断用户名是否符合规范
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        if (!empName.matches(regx)) {
            return Msg.fail().add("va_msg", "要求2~5位汉字或者6~16位字符(字母或下划线)");
        }

        //数据库用户名重复校验
        boolean check_flag = employeeService.checkUser(empName);
        if (check_flag) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "用户名已被注册");
        }
    }

    /**
     * 员工保存
     *
     * @param employee
     * @param result
     * @return
     * @Valid 对Employee类中字段校验的实现
     */
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result) {
        if (result.hasErrors()) {
            //如果校验失败,把校验失败的错误信息返回到模态框
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("错误的字段名:" + fieldError.getField());
                System.out.println("错误信息:" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        } else {
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }

    /**
     * 查询所有员工数据
     *
     * @param pn
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        //引入PageHelper分页插件
        PageHelper.startPage(pn, 5);//从pn页开始，每页5条数据
        List<Employee> emps = employeeService.getAll();
        //使用pageInfo包装查询结果，pageInfo里封装里详细分页信息
        PageInfo page = new PageInfo(emps, 5);//连续显示5页
        //
        return Msg.success().add("pageInfo", page);
    }

    //查询所有员工数据（分页查询 pn=PageNumber）
//    @RequestMapping("/emps")
//    public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
//        //引入PageHelper分页插件
//        PageHelper.startPage(pn,5);//从pn页开始，每页5条数据
//        List<Employee> emps = employeeService.getAll();
//        //使用pageInfo包装查询结果，pageInfo里封装里详细分页信息
//        PageInfo page = new PageInfo(emps,5);//连续显示5页
//        //把选中页查询出的数据交给页面
//        model.addAttribute("pageInfo",page);
//        return "empList";
//    }
}
